package com.erp.programmer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erp.programmer.bean.CodeMsg;
import com.erp.programmer.dao.SaleOrderDetailMapper;
import com.erp.programmer.dao.SaleOrderMapper;
import com.erp.programmer.dao.StockOrderMapper;
import com.erp.programmer.domain.SaleOrder;

import com.erp.programmer.domain.SaleOrderDetail;
import com.erp.programmer.domain.StockOrder;
import com.erp.programmer.dto.*;

import com.erp.programmer.enums.PaymentStateEnum;
import com.erp.programmer.utils.CommonUtil;
import com.erp.programmer.utils.CopyUtil;
import com.erp.programmer.dao.OutWarehouseOrderMapper;
import com.erp.programmer.domain.OutWarehouseOrder;
import com.erp.programmer.service.IOutWarehouseOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Takagi3
 * @since 2021-05-26
 */
@Service
@Transactional
public class OutWarehouseOrderServiceImpl extends ServiceImpl<OutWarehouseOrderMapper, OutWarehouseOrder> implements IOutWarehouseOrderService {


    
    @Autowired
    SaleOrderMapper saleOrderMapper;
    
    @Autowired
    StockOrderMapper stockOrderMapper;

    @Autowired
    OutWarehouseOrderMapper outWarehouseOrderMapper;
    @Autowired
    SaleOrderDetailMapper saleOrderDetailMapper;

    //生成出库单
    public ResponseDto<PageDto<OutWarehouseOrderDto>> saveOutWarehouseOrder(SaleOrderDto saleOrderDto)
    {
        //业务逻辑：传进参数销售订单，根据销售订单，减少对应商品库存，生成出库单

        //查找销售订单
        QueryWrapper<SaleOrder> saleOrderQueryWrapper = new QueryWrapper<>();
        saleOrderQueryWrapper.eq("id",(saleOrderDto.getId()));
        saleOrderDto=CopyUtil.copy(saleOrderMapper.selectOne(saleOrderQueryWrapper),SaleOrderDto.class);
        //销售订单是否成功查找
        if(saleOrderDto==null)
        {
            return ResponseDto.errorByMsg(CodeMsg.ORDER_NOT_EXIST);
        }
        //验证该销售订单是否已生成过库存单
        QueryWrapper<OutWarehouseOrder>  outWarehouseOrderQueryWrapper = new QueryWrapper<>();
        outWarehouseOrderQueryWrapper.eq("sale_order_number",saleOrderDto.getId());
        if (outWarehouseOrderMapper.selectOne(outWarehouseOrderQueryWrapper)!=null) {
            return ResponseDto.errorByMsg(CodeMsg.OUT_WAREHOUSE_ERROR);
        }
        //验证销售订单是否支付
        if(saleOrderDto.getPaymentState()!=PaymentStateEnum.PAYED.getCode())
        {
            return ResponseDto.errorByMsg(CodeMsg.ORDER_NOT_PAYED);
        }

        // new出库单对象
        OutWarehouseOrderDto outWarehouseOrderDto=new OutWarehouseOrderDto();
        //设置出库单对应销售单ID
        outWarehouseOrderDto.setSaleOrderNumber(saleOrderDto.getId());
        //设置出库单总价
        outWarehouseOrderDto.setTotalPriec(saleOrderDto.getTotalPrice());
        //设置出库时间
        outWarehouseOrderDto.setOutWarehouseData(new Date());

        //定义商品数量最终结果
        BigDecimal numberResult;


        //定义设置销售详单选择器，生成对应销售详单
        QueryWrapper<SaleOrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("sale_order_number",(saleOrderDto.getId()));
        List<SaleOrderDetailDto> saleOrderOrderDtoList = CopyUtil.copyList(saleOrderDetailMapper.selectList(queryWrapper1), SaleOrderDetailDto.class);
        StockOrderDto stockOrderDto =new StockOrderDto();


        BigDecimal bigDecimal = null;
        BigDecimal bigDecimal1=null;
        for(SaleOrderDetailDto saleOrderDetailDto:saleOrderOrderDtoList) {

            //获取详单的商品数量

            bigDecimal=  new BigDecimal(saleOrderDetailDto.getNumber());
            //获取详单的商品Id


            //设置搜索条件，查询库存单，商品存单
            stockOrderDto=CopyUtil.copy(stockOrderMapper.selectOne(new QueryWrapper<StockOrder>().eq("product_id",(saleOrderDetailDto.getProductId()))),StockOrderDto.class);
            bigDecimal1=new BigDecimal(stockOrderDto.getNumber());
            //
            if(bigDecimal1.compareTo(bigDecimal)>0) {
                numberResult = bigDecimal1.subtract(bigDecimal);
                stockOrderDto.setNumber(numberResult.toString());
            }
            else {
                return ResponseDto.errorByMsg(CodeMsg.PRODUCT_NUM_ERROR);
            }
            //Dto转换
            StockOrder stockOrder=CopyUtil.copy(stockOrderDto,StockOrder.class);
            //数据库更新库存单内商品数量
            if (stockOrderMapper.updateById(stockOrder)<1) {
                return ResponseDto.errorByMsg(CodeMsg.PRODUCT_NUM_ERROR);
            }
        }

        //Dto转换
        //生成出库单
        OutWarehouseOrder outWarehouseOrder = CopyUtil.copy(outWarehouseOrderDto, OutWarehouseOrder.class);
        if(outWarehouseOrderMapper.insert(outWarehouseOrder)<1) {
            return ResponseDto.errorByMsg(CodeMsg.SUBMIT_ORDER_ERROR);
        }

        //随后更新数据库销售单完成时间
        saleOrderDto.setCompleteData(new Date());
        SaleOrder saleOrder = CopyUtil.copy(saleOrderDto, SaleOrder.class);
        if (saleOrderMapper.updateById(saleOrder)<1) {
            return ResponseDto.errorByMsg(CodeMsg.UPDATE_ORDER_COMPLETE_DATE_ERROR);
        }


        ResponseDto<PageDto<OutWarehouseOrderDto>> outWarehouseOrders = getOutWarehouseOrders(new PageDto<OutWarehouseOrderDto>());
        outWarehouseOrders.setMsg("添加成功");

        return outWarehouseOrders;

    }

    /**
     * 根据条件获取订单信息，无条件返回全部
     * @param pageDto
     * @return
     */
    @Override
    public ResponseDto<PageDto<OutWarehouseOrderDto>> getOutWarehouseOrders(PageDto<OutWarehouseOrderDto> pageDto) {
        QueryWrapper<OutWarehouseOrder> queryWrapper = new QueryWrapper<>();
        if ("id".equals(pageDto.getSearchType()) && !CommonUtil.isEmpty(pageDto.getSearchContent())) {
            queryWrapper.eq("id",pageDto.getSearchContent());
        }
        if (pageDto.getPage() ==null) {
            pageDto.setPage(1);
        }
        pageDto.setSize(5);
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        List<OutWarehouseOrder> outWarehouseOrderList = outWarehouseOrderMapper.selectList(queryWrapper);
        List<OutWarehouseOrderDto> outWarehouseOrderOrderDtoList = CopyUtil.copyList(outWarehouseOrderList, OutWarehouseOrderDto.class);
        PageInfo<OutWarehouseOrder> pageInfo = new PageInfo<>(outWarehouseOrderList);
        pageDto.setTotal(pageInfo.getTotal());
        pageDto.setList(outWarehouseOrderOrderDtoList);
        return ResponseDto.success(pageDto);
    }
}
